#!/usr/bin/python

import sys, os
import scapy
import socket
import fcntl
import struct
import readline
import termext

scapy.conf.iface = 'eth0'

stdin, stdout = os.popen2('whoami')
if stdout.readline().strip() != 'root':
	print "You must be root to run this script.\n"
	sys.exit(1)

#from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/439094
def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15]))[20:24])


term = termext.TerminalController()

def hunt_macs():
	octects = "85.85.186.90".split('.') #get_ip_address(scapy.conf.iface).split('.')
	ip = ""
	for i in range(0,3):
		ip += octects[i]
		ip += '.'

	hunted = []
	unanswered = []

	pbar = termext.ProgressBar(term, "Scanning...")
	pbar.BAR = pbar.REDBAR
	for i in range(1,255):
		net = ip + str(i)
		ans,unans = scapy.srp(scapy.Ether(dst="ff:ff:ff:ff:ff:ff")/scapy.ARP(pdst=ip + str(i)), filter="arp and arp[7] = 2", timeout=0.01, iface_hint=net, verbose=0)
		mac = ""
		ipaddr = net
		if ans:
			ether, arp = ans[0]
			mac = arp.src
			hunted.append ((mac, ipaddr))
		else:
			mac = "No response"
			unanswered.append ((mac, ipaddr))

		pbar.update(float(i)/254, "IP: %s MAC: %s" % (ipaddr, mac))
		if i < 255/3:
			pass
		elif i >= 255/3 and i <= (255)*2/3:
			pbar.BAR = pbar.YELLOWBAR
		else:
			pbar.BAR = pbar.GREENBAR
	
	return hunted, unanswered

def print_results():
	hunted, unanswered = hunt_macs()
	print ""
	print ("**********" + term.YELLOW + term.BOLD + " SUCCESSFULL REQUESTS " + term.NORMAL + "**********").center(term.COLS)
	for ether, ipaddr in hunted:
		print "[%s%s%s, %s%s%s]" % (term.GREEN + term.BOLD,ether,term.NORMAL,term.YELLOW + term.BOLD,ipaddr,term.NORMAL)

	print "\n\n"
	print ("**********" + term.YELLOW + term.BOLD + " UNANSWERED REQUESTS " + term.NORMAL + "**********").center(term.COLS)
	for ether, ipaddr in unanswered:
		print "[%s%s%s, %s%s%s]" % (term.GREEN + term.BOLD,ether,term.NORMAL,term.YELLOW + term.BOLD,ipaddr,term.NORMAL)


def print_macintosh(hunted):
	applemacs = []
	file = open('apple-oui.db', 'r')
	for i in file.readlines():
		applemacs.append (i.split()[2])
	for h in hunted:
		if h[0][:8] in applemacs:
			print "Mac Found!!! IP: %s MAC: %s" % (h[0], h[1])

hunted, unanswered = hunt_macs()
print_macintosh(hunted)

